package com.net.xpay.common.validator;


import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayFundAccountbookQueryResponse;
import com.google.common.base.Strings;
import com.net.xpay.common.domain.User;
import com.net.xpay.common.domain.UserProfile;
import com.net.xpay.common.domain.UserShard;
import com.net.xpay.common.enums.config.CommonSysConfigKey;
import com.net.xpay.common.helper.CommonSysConfigHelper;
import com.net.xpay.common.manager.UserManager;
import com.net.xpay.common.manager.UserProfileManager;
import com.net.xpay.common.manager.UserShardManager;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.domain.safePay.SafePayBookAccount;
import com.net.xpay.core.enums.SafePayBookAccountAuditStatus;
import com.net.xpay.core.enums.SafePayBookAccountBookStatus;
import com.net.xpay.core.manager.safePay.SafePayBookAccountManager;
import com.net.common.exception.BusinessException;
import com.net.xpay.alipay.safePay.PoseidonSafePayAlipayClient;
import com.net.shard.ShardUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * 合伙人账户提现验证
 */
@Component
@Slf4j
public class AdminPartnerAccountWithdrawValidator {

    @Autowired
    private CommonSysConfigHelper commonSysConfigHelper;

    @Autowired
    private UserManager userManager;

    @Autowired
    private UserShardManager userShardManager;

    @Autowired
    private SafePayBookAccountManager safePayBookAccountManager;

    @Autowired
    private UserProfileManager userProfileManager;

    @Autowired
    private PoseidonSafePayAlipayClient xpaySafePayAlipayClient;



    //检查一下公司的安全发记账本余额是否足够

    /**
     * @param transAmount 提现金额 单位元
     */
    public void validateSafePayAccountEnough(BigDecimal transAmount) {
        log.info("validateSafePayAccountEnough transAmount={}", transAmount);
        //打款支付宝和打款手机号
        String alipayAccount = commonSysConfigHelper.getString(CommonSysConfigKey.PARTNER_WITHDRAW_SAFE_PAY_ACCOUNT);
        String sysMobile = commonSysConfigHelper.getString(CommonSysConfigKey.PARTNER_WITHDRAW_MOBILE);
        if (Strings.isNullOrEmpty(alipayAccount) || Strings.isNullOrEmpty(sysMobile)) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "请配置系统安全发打款账号");
        }

        User transUser = userManager.findByMobile(sysMobile);
        if (transUser == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "系统打款账号不存在");
        }
        UserShard shard = userShardManager.getById(transUser.getId());

        try {
            ShardUtil.setShardContext(shard.getShardId());
            SafePayBookAccount safePayBookAccount = safePayBookAccountManager.findByAlipayNickName(transUser.getId(), alipayAccount);
            //检查下记账本的状态是否正常
            checkSafePayBookAccount(safePayBookAccount);

            //检查记账本余额
            checkSafePayBookMoneyEnough(safePayBookAccount, transAmount);
        } finally {
            ShardUtil.cleanShardContext();
        }
    }


    private void checkSafePayBookAccount(SafePayBookAccount safePayBookAccount) {
        if (safePayBookAccount == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "付款支付宝账号不存在");
        }
        if (safePayBookAccount.getBookId() == null || !SafePayBookAccountBookStatus.YES.equals(safePayBookAccount.getBookStatus())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "尚未开通资金账本，无法转账");
        }

        UserProfile userProfile = userProfileManager.getById(safePayBookAccount.getUserId());
        if (!Boolean.FALSE.equals(userProfile.getNeedSafePayAuth())) {
            if (safePayBookAccount.getAuditStatus() == SafePayBookAccountAuditStatus.INIT || safePayBookAccount.getAuditStatus() == SafePayBookAccountAuditStatus.FAIL) {
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "企业支付宝尚未通过认证，请先认证");
            }

            if (safePayBookAccount.getAuditStatus() == SafePayBookAccountAuditStatus.AUDITING) {
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "企业支付宝认证尚在审核中，请耐心等待");
            }
        }
    }

    private void checkSafePayBookMoneyEnough(SafePayBookAccount safePayBookAccount, BigDecimal transAmount) {
        AlipayFundAccountbookQueryResponse resp;
        try {
            resp = xpaySafePayAlipayClient.queryAlipayFundAccountbook(safePayBookAccount.getBookId(), safePayBookAccount.getAgreementNo());

            if (resp.isSuccess()) {
                String availableAmount = resp.getAvailableAmount();
                log.info("checkSafePayBookMoneyEnough availableAmount={}|transAmount={}", availableAmount, transAmount);
                if (new BigDecimal(availableAmount).compareTo(transAmount) < 0) {
                    throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "账户余额不足");
                }
            } else {
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "转账方余额查询失败：" + resp.getMsg() + "|" + resp.getSubMsg());
            }
        } catch (AlipayApiException e) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "查询安全发记账本异常");
        }

    }

}
